package ch.jhc.sevlet;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import org.apache.commons.dbutils.QueryRunner;

import ch.jhc.Global;
import ch.jhc.bean.User;
import ch.jhc.db.UserDao;




@WebServlet("/MultiPartRegisterSevlet")
@MultipartConfig(maxRequestSize=10485760)

public class MultiPartRegisterSevlet extends HttpServlet implements Global{
	private static final long serialVersionUID = 1L;
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		//code取出来 比较
		String vcode = getContent(request.getPart("Vcode"));
		String expected = (String) request.getSession().getAttribute(Global.VCODE_KEY);
		if(!vcode.equalsIgnoreCase(expected)) {
			response.sendRedirect("./register.jsp");
			return;
		}
		
		String contextPath = request.getServletContext().getRealPath("/upload");
		File uploadDir = new File(contextPath);
		if(!uploadDir.exists()) {
			uploadDir.mkdirs();
		}
		
		//System.out.println(contextPath);
		Part part = request.getPart("file");
		String filename = part.getSubmittedFileName();
		String extName = filename.substring(filename.lastIndexOf("."));
		if(!extName.equalsIgnoreCase(".jpg") && !extName.equalsIgnoreCase(".png")) {
			throw new ServletException("Not supported image type");
		}
		String diskFilename = System.currentTimeMillis() + extName;
		String diskFile = contextPath + File.separator + diskFilename;
		part.write(diskFile);
		System.out.println(diskFile);

		
		// return VCode true or false
		//HttpSession httpSession = request.getSession();
		// String VCode = new String((StringBuffer)httpSession.getAttribute("VCode"));
		//String VCode = (String) httpSession.getAttribute("VCode");
		boolean flag = false;

		
		
		Map<String, String> map = new HashMap<>();
		for (Part part2 : request.getParts()) {

			if (part2.getName().equals("file")) {
				continue;
			}
			String content = getContent(part2);
			String key = part2.getName();
			if (map.get(key) == null) {
				map.put(key, content);
			} else {
				String newValue = map.get(key) + "," + content;
				map.put(key, newValue);
			}
			System.out.println("content: "+ content + "VCode: "+expected);
			if (content.equalsIgnoreCase(expected)) {
				flag =true;
			}
		}
		
		System.out.println(map.toString());
		
		/*if(flag) {
			request.setAttribute("message", "登陆成功！");
			System.out.println("登录成功");
			request.getRequestDispatcher("/register.jsp").forward(request, response);
		} else {
			request.setAttribute("message", "登陆失败！");
			System.out.println("登录失败");
			request.getRequestDispatcher("/register.jsp").forward(request, response);
			return;
		}*/
		if(flag) {
			request.setAttribute("message", "注册成功！");
			System.out.println("注册成功");
			//response.sendRedirect("./upload/" + diskFilename);
			response.sendRedirect("./login.jsp");
		} else {
			request.setAttribute("message", "注册失败！");
			System.out.println("注册失败");
			request.getRequestDispatcher("/wode.jsp").forward(request, response);
			return;
		}
		
		
		//TODO:保存到数据库中。
		QueryRunner runner = (QueryRunner)request.getServletContext().getAttribute("runner");
		User User = new User(map.get("username"),map.get("pwd"),diskFilename,map.get("sex"),map.get("interests"));
		try {
			UserDao.register(runner, User);
			} catch (SQLException e) {
			e.printStackTrace();
			response.sendError(500);
			return;
		}
		//跳转到另一个页面的网址
		//response.sendRedirect("./upload/" + diskFilename);
	}
	
	private String getContent(Part part) throws IOException {
		try(Scanner scanner = new Scanner(part.getInputStream())){
			return scanner.next();
		}
	}

}